package com.ikkong.qy.util;

import java.util.Map;

import javax.servlet.http.HttpSession;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.kit.HttpKit;

public class WeixinTicketManager {
	
	private  String TICKET = "";			//网页的ticket
	private  long EXPIRES_TIME = 0l;					//过期时间
	private  Thread getTokenThread = null;
	
	public String getEnableTicket(String token) {
		String result = "";
		if (StringUtils.isEmpty(TICKET)) {
			try {
				result = getChatTicket(token);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		long diff = EXPIRES_TIME - System.currentTimeMillis();
		if (diff > 60) {
			return TICKET;
		} else if (diff > 10) {
			if (getTokenThread == null) {
				synchronized (this) {
					if (getTokenThread == null) {
						getTokenThread = new GetJsTokenThread(token);
						getTokenThread.start();
					}
				}
			}
			return TICKET;
		} else {
			try {
				result = getChatTicket(token);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

	}

	private synchronized String getChatTicket(String token) throws Exception {
		String resp = "";
		resp = HttpKit.get("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+token, null);
		Map<String, Object> resultMap = CommonUtils.getJsonMap(resp);

		String ticket = (String) resultMap.get("ticket");
		long expires_time = Long.parseLong(resultMap.get("expires_in").toString());
		CommonUtils.tPrint(resultMap, "ticket");
		
		setConfigStr(ticket, expires_time*1000);
		return ticket;
	}

	private void setConfigStr(String ticket, long expires_time) {
		EXPIRES_TIME = System.currentTimeMillis() + expires_time;
		TICKET = ticket;
	}

	class GetJsTokenThread extends Thread {
		
		private String token;
		public GetJsTokenThread(String token){
			this.token = token;
		}
		
		@Override
		public void run() {
			try {
				getChatTicket(token);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				getTokenThread = null;
			}
		}
	}
}
